<?php

namespace app\models;
use yii\helpers\ArrayHelper;
use app\models\Languages;
use app\models\NewsCategory;
use Yii;

/**
 * This is the model class for table "{{%project_category}}".
 *
 * @property int $id
 * @property string $parent_id 上级id
 * @property string $name 分类名称
 */
class NewsCategory extends \yii\db\ActiveRecord
{   
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%news_category}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name'], 'required', 'message' => '分类名称不能为空'],
            [['parent_id'], 'integer'],
            [['name'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'parent_id' => Yii::t('app', '父类'),
            'name' => Yii::t('app', '名称（后台）'),
        ];
    }

    //找到分类 以及下的所有子分类id
    public static function getChildCategory($id){
        $childCategoryInfo = self::find()->where(['parent_id' => $id])->asArray()->indexBy('id')->all();
        $ids = array_keys($childCategoryInfo);
        if ($id) {
            array_unshift($ids, $id);
        }
        return $ids;
    }


    //删除分类下的所有子分类
    // public static function deleteCategory($id){
    //     self::deleteAll(['parent_id' => $id]);

    //     self::findOne($id)->delete();
    // }

    public function subtree($arr,$id=0,$lev=1){
        $subs = array(); // 子孙数组
        foreach($arr as $v) {
          if($v['parent_id'] == $id) {
            $v['lev'] = $lev;
            $subs[] = $v; // 举例说找到array('id'=>1,'name'=>'安徽','parent'=>0),
            $subs = array_merge($subs,$this->subtree($arr,$v['id'],$lev+1));
          }
        }
        return $subs;
    }

    //计算下拉表数据
    public function getDropDownList($res = null){
        //增加顶级分类选项
        $arr=array(
          'new_cat_name'=>'顶级分类',
          'id'=>0
        );

        if ($res === null) {
            $res = $this->getAllCategory();
            $arr = [];
        }

        $tree = $this->subtree($res,0,1);

        foreach($tree as $k=> $v) {
          $tree[$k]['new_cat_name']=str_repeat('--',$v['lev']).$v['name'].str_repeat('--',$v['lev']); //str_repeat — 重复一个字符串
        }
        
        if (!empty($arr)) {
            array_unshift($tree,$arr);
        }

        return ArrayHelper::map($tree,'id','new_cat_name');
    }

    //获取所有分类
    public function getAllCategory($indexby = null){
        if (is_null($indexby)) {
            return self::find()->asArray()->all();
        }
        return self::find()->asArray()->indexBy($indexby)->all();
    }

    //取出分类的名称
    public function getCategoryName($id = null){
        $data = $this->getAllCategory('id');
        if (isset($data[$id]['name'])) {
            return $data[$id]['name'];
        }
        return false;
    }


    public function getLanguages()
    {
        return $this->hasMany(Languages::className(), ['table_id' => 'id']);
            // ->where(['table_field'=>'real_name','table_name'=>'{{%project_category}}']);
    }
}
